/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */

/**
 * Context Menu Listener.
 *
 * @author Alexander Kozlov
 */
function wsshContextMenuListener()
{
    this.logger = yrprxFactory.createLogger("wsshContextMenuListener");

    this.slideShowItemId = null;
    this.slideShowAllItemId = null;

    this.addViewFullScreenItem();
    this.addSlideShowItem();
    this.updateSlideShowAll();

    this.subscribeToEvents();
}

wsshContextMenuListener.prototype.subscribeToEvents = function()
{
    try
    {
        var listener = this;

        var updateSlideShow = function() {
            listener.updateSlideShow();
        };

        chrome.tabs.onActivated.addListener(updateSlideShow);

        var updateSlideShowAndSlideShowAll = function() {
            listener.updateSlideShow();
            listener.updateSlideShowAll();
        };

        chrome.tabs.onUpdated.addListener(updateSlideShowAndSlideShowAll);
        chrome.windows.onFocusChanged.addListener(updateSlideShowAndSlideShowAll);

        var updateSlideShowAll = function() {
            listener.updateSlideShowAll();
        };

        chrome.tabs.onAttached.addListener(updateSlideShowAll);
        chrome.tabs.onCreated.addListener(updateSlideShowAll);
        chrome.tabs.onDetached.addListener(updateSlideShowAll);
        chrome.tabs.onRemoved.addListener(updateSlideShowAll);

        this.rulesObserver = {
            observe: function(subject, topic, data) {
                listener.updateSlideShow(true);
            }
        };

        // update menu when rules was imported
        yrprxObserverServiceHelper.addObserver(this.rulesObserver, WEBSLIDESHOW_UPDATE_RULES_EVENT);
        yrprxObserverServiceHelper.addObserver(this.rulesObserver, WEBSLIDESHOW_UPDATE_CONFIGURATION_EVENT);

    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("subscribeToEvents: ", ex);
    }
}

wsshContextMenuListener.prototype.addViewFullScreenItem = function()
{
    try
    {
        var listener = this;

        var onViewFullScreen = function (info, tab) {
            listener.onViewFullScreen(info, tab);
        };

        chrome.contextMenus.create({"title": chrome.i18n.getMessage("webslideshow_context_menu_view_full_screen_label"), "contexts":["image"], "onclick": onViewFullScreen});
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("addViewFullScreenItem: ", ex);
    }
}

wsshContextMenuListener.prototype.addSlideShowItem = function()
{
    try
    {
        if (this.slideShowItemId)
            return;

        var listener = this;

        var onSlideShow = function (info, tab) {
            listener.onSlideShow(info, tab);
        };

        this.slideShowItemId = chrome.contextMenus.create({"title": chrome.i18n.getMessage("webslideshow_context_menu_slide_show_label"), "contexts":["page"], "onclick": onSlideShow});

        if (this.slideShowAllItemId) // SlideShowAll is already here, let's recreate to move it down.
        {
            this.removeSlideShowAllItem();
            this.addSlideShowAllItem();
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("addSlideShowItem: ", ex);
    }
}

wsshContextMenuListener.prototype.removeSlideShowItem = function()
{
    try
    {
        if (!this.slideShowItemId)
            return;

        chrome.contextMenus.remove(this.slideShowItemId);
        this.slideShowItemId = null;
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("removeSlideShowItem: ", ex);
    }
}

wsshContextMenuListener.prototype.updateSlideShow = function(force)
{
    try
    {
        var listener = this;

        chrome.tabs.query({ 'currentWindow': true, 'active': true, 'status': 'complete', 'url': '*://*/*' }, function (tabs) {
            if (!tabs.length) // skip it
                listener.removeSlideShowItem();
            else
            {
                var tab = tabs[0];

                var onImageCounted = function(response) {
                    if (response.returnedValue > 1)
                        listener.addSlideShowItem();
                    else
                        listener.removeSlideShowItem();
                };

                if (force)
                    chrome.tabs.sendMessage(tab.id, {call: "getImagesCount", args: [force, wsshConfig.clone(), g_wsshImageResolver.getItems()]}, onImageCounted);
                else
                    chrome.tabs.sendMessage(tab.id, {call: "getImagesCount"}, function(response) {
                        if (response.returnedValue == "NotYetInitialized") // try one more time
                            chrome.tabs.sendMessage(tab.id, {call: "getImagesCount", args: [false, wsshConfig.clone(), g_wsshImageResolver.getItems()]}, onImageCounted);
                        else
                            onImageCounted(response);
                    });
            }
        });
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("updateSlideShow: ", ex);
    }
}

wsshContextMenuListener.prototype.addSlideShowAllItem = function()
{
    try
    {
        if (this.slideShowAllItemId)
            return;

        var listener = this;

        var onSlideShowAll = function (info, tab) {
            listener.onSlideShowAll(info, tab);
        };

        this.slideShowAllItemId = chrome.contextMenus.create({"title": chrome.i18n.getMessage("webslideshow_context_menu_slide_show_all_label"), "contexts":["page"], "onclick": onSlideShowAll});
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("addSlideShowAllItem: ", ex);
    }
}

wsshContextMenuListener.prototype.removeSlideShowAllItem = function()
{
    try
    {
        if (!this.slideShowAllItemId)
            return;

        chrome.contextMenus.remove(this.slideShowAllItemId);
        this.slideShowAllItemId = null;
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("removeSlideShowAllItem: ", ex);
    }
}

wsshContextMenuListener.prototype.updateSlideShowAll = function()
{
    try
    {
        var listener = this;

        chrome.tabs.query({ 'currentWindow': true, 'status': 'complete', 'url': '*://*/*' }, function (tabs) {
            if (tabs.length > 1)
                listener.addSlideShowAllItem();
            else
                listener.removeSlideShowAllItem();
        });
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("updateSlideShowAll: ", ex);
    }
}

wsshContextMenuListener.prototype.onViewFullScreen = function(info, tab)
{
    try
    {
        var url = g_wsshImageResolver.resolveImageURL(info.srcUrl, info.linkUrl, tab.url);

        wsshWindowManager.openSlideShow([url], tab.title);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("onViewFullScreen: ", ex);
    }
}

wsshContextMenuListener.prototype.onSlideShow = function(info, tab)
{
    try
    {
        chrome.tabs.sendMessage(tab.id, {call: "startSlideShow"});
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("onSlideShow: ", ex);
    }
}

wsshContextMenuListener.prototype.onSlideShowAll = function(info, tab)
{
    try
    {
        chrome.tabs.query({'windowId': tab.windowId}, function(tabs) {
            var waitFor = tabs.length;
            var forceUseTheLastWindow = false;
            for (var i in tabs)
            {
                var tab = tabs[i];

                if (tab.status != "complete" || tab.url && tab.url.indexOf("http://") != 0 && tab.url.indexOf("https://") != 0) { // skip it
                    --waitFor;
                    continue;
                }

                chrome.tabs.sendMessage(tab.id, {call: "findImages"}, function(response) {
                    var newImages = response.returnedValue.images;
                    var title = response.returnedValue.title;
                    if (newImages && newImages.length)
                    {
                        if (forceUseTheLastWindow && !wsshWindowManager.theLastSlideShowDialog) // dialog opening is in-progress
                        {
                            wsshWindowManager.theLastSlideShowDialogListeners.push(function () {
                                wsshWindowManager.openSlideShow(newImages, title, true);
                                wsshWindowManager.theLastSlideShowDialogListener = null;
                            });
                        }
                        else
                        {
                            wsshWindowManager.openSlideShow(newImages, title, forceUseTheLastWindow);
                            forceUseTheLastWindow = true;
                        }
                    }

                    if (--waitFor == 0 && !forceUseTheLastWindow)
                        yrprxPrompt.alert(wsshResources["webslideshow.title"], wsshResources["webslideshow.can.not.find.appropriate.images"]);
                });
            }
        });
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("onSlideShow: ", ex);
    }
}

var WSSH_ContextMenuListener = new wsshContextMenuListener();